using UnityEngine;
using UnityEngine.UI;

namespace PP.Basic
{
    /// <summary>
    /// DeformableImage 可变形的 Image
    /// </summary>
    [RequireComponent(typeof(CanvasRenderer))]
    public class DeformableImage : Image
    {
        [SerializeField]
        private Vector2 _leftTopOffset;//左上
        [SerializeField]
        private Vector2 _leftBottomOffset;//左下
        [SerializeField]
        private Vector2 _rightTopOffset;//右上
        [SerializeField]
        private Vector2 _rightBottomOffset;//右下

        public void UpdateMesh()
        {
            SetVerticesDirty();
        }

        protected override void OnPopulateMesh(VertexHelper vh)
        {
            base.OnPopulateMesh(vh);
            int vertexCount = vh.currentVertCount;
            for (int i = 0; i < vertexCount; i++)
            {
                UIVertex vertex = new UIVertex();
                vh.PopulateUIVertex(ref vertex, i);
                vertex.position += GetOffset(i);
                vh.SetUIVertex(vertex, i);
            }
        }

        /// <summary>
        /// 获取偏移量
        /// </summary>
        private Vector3 GetOffset(int i)
        {
            if (i == 0)
            {
                return _leftBottomOffset;
            }
            else if (i == 1)
            {
                return _leftTopOffset;
            }
            else if (i == 2)
            {
                return _rightTopOffset;
            }
            else if (i == 3)
            {
                return _rightBottomOffset;
            }
            return Vector3.zero;
        }
    }
}
